/*
 * 
 * 
 * 
 */
package com.hboxs.asl.dao.impl;

import com.hboxs.asl.Page;
import com.hboxs.asl.Pageable;
import com.hboxs.asl.dao.CouponDao;
import com.hboxs.asl.entity.Coupon;
import com.hboxs.asl.entity.Member;
import org.springframework.stereotype.Repository;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Date;
import java.util.List;

/**
 * Dao - 优惠券
 */
@Repository("couponDaoImpl")
public class CouponDaoImpl extends BaseDaoImpl<Coupon, Long> implements CouponDao {

    public Page<Coupon> findPage(Boolean isEnabled, Boolean isExchange, Boolean hasExpired, Pageable pageable) {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<Coupon> criteriaQuery = criteriaBuilder.createQuery(Coupon.class);
        Root<Coupon> root = criteriaQuery.from(Coupon.class);
        criteriaQuery.select(root);
        Predicate restrictions = criteriaBuilder.conjunction();
        if (isEnabled != null) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isEnabled"), isEnabled));
        }
        if (isExchange != null) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isExchange"), isExchange));
        }
        if (hasExpired != null) {
            if (hasExpired) {
                restrictions = criteriaBuilder.and(restrictions, root.get("endDate").isNotNull(), criteriaBuilder.lessThan(root.<Date>get("endDate"), new Date()));
            } else {
                restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(root.get("endDate").isNull(), criteriaBuilder.greaterThanOrEqualTo(root.<Date>get("endDate"), new Date())));
            }
        }
        criteriaQuery.where(restrictions);
        return super.findPage(criteriaQuery, pageable);
    }

    @Override
    public List<Coupon> findEnableCoupons() {
        String queryString = "SELECT coupon FROM Coupon AS coupon " +
                "WHERE coupon.isEnabled=true AND current_timestamp < coupon.endDate ";
        return entityManager.createQuery(queryString).getResultList();

    }

    @Override
    public Long findReceivableCount4Coupon(Member member, Coupon coupon) {
        String queryStr = "SELECT COUNT(couponCode) FROM CouponCode AS couponCode JOIN couponCode.coupon AS coupon " +
                "WHERE couponCode.member=:member AND couponCode.coupon=:coupon ";
        Long result = (Long) entityManager.createQuery(queryStr).setParameter("member", member).setParameter("coupon", coupon).getSingleResult();
        return coupon.getReceivableNum() - result;
    }

}